import React, { useCallback, useContext, useLayoutEffect, useReducer } from "react";


// 1. 创建context对象
interface IDefaultValue {
    [key: string]: any
}
const defaultValue:IDefaultValue = {}
const Context = React.createContext(defaultValue)

// 2. 使用context创建provider来传递value
interface IProvider {
    value: any
    children: React.ReactNode
}
export function Provider({value, children}: IProvider) {
    return (
        <Context.Provider value={value} >{children}</Context.Provider>
    )
}

// 3. 子组件使用context
// useContext contextType consumer



// forceUpdate
export function useForceUpdate() {
    const [, forceUpdate] = useReducer(x => x + 1, 0)
    const update = useCallback(() => {
        forceUpdate()
    }, [])
    return update
}

// useDispatch
export function useDispatch() {
    return useContext(Context).dispatch
}

export function useSelector(selector: Function) {
    const store = useContext(Context)

    const selectedState = selector(store.getState())

    const forceUpdate = useForceUpdate()

    useLayoutEffect(() => {
        const unsubscribe = store.subscribe(() => {
            forceUpdate()
        })
        return () => {
            unsubscribe()
        }
    }, [store])

    return selectedState

}

